<?php

namespace App\Http\Controllers\Administrator\Game;

use Carbon\Carbon;
use App\Models\User;
use Ramsey\Uuid\Uuid;
use App\Models\Conf\Site;
use App\Models\Log\Earning;
use Illuminate\Http\Request;
use App\Models\Log\SiteScore;
use Dingo\Api\Routing\Helpers;
use App\Models\Log\SiteDeposit;
use App\Models\Def\MainGamePlat;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests\Administrator\SiteRequest;

class SiteController extends Controller
{
    use Helpers;

    protected $roleName = 'site_role';

    /**
     * gameapi
     * 2018/10/8 14:48
     * Administrator
     * index
     * Display a listing of the resource
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function index(Site $site)
    {
        $this->authorize('index', $site);
        $siteIds = $this->getCurrentUserSite();
        $sites = Site::whereIn('id', $siteIds)->with(['user', 'agent'])->paginate(config('administrator.paginate.limit'));
        return view('backend.game.site.index', compact('sites'));
    }

    /**
     * gameapi
     * 2018/10/8 14:49
     * Administrator
     * create
     * Show the form for creating a new resource.
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function create(Site $site)
    {
        $this->authorize('create', $site);
        if ($site->agent) {
            $plats = $site->agent->mainGamePlats()->where('conf_agent_main_game_plats.status', 1)->get()->toArray();
        } else {
            $plats = MainGamePlat::status()->get()->toArray();
        }
        $sitePlats = [];
        return view('backend.game.site.create_and_edit', compact('site', 'plats', 'sitePlats'));
    }

    /**
     * gameapi
     * 2018/11/3 13:20
     * Administrator
     * store
     * Store a newly created resource in storage.
     * @param SiteRequest $request
     * @param Site $site
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function store(SiteRequest $request, Site $site)
    {
        $this->authorize('create', $site);
        DB::beginTransaction();
        $data = $request->only(['site_name', 'username', 'is_external', 'status',]);
        $userData = array_merge($request->only(['name', 'password']), ['type' => 2]);
        $user = User::create($userData);
        $roles = Role::where('name', $this->roleName)->get()->pluck('id')->toArray();
        $user->assignRole($roles);
        $agent_id = $this->userIdentity();
        $data = array_merge($data, ['user_id' => $user->id, 'agent_id' => $agent_id, 'token' => encrypt($userData['name'] . $data['username'])]);
        $site = Site::create($data);

        //创建网站平台关联
        $platParam = $request->plats;

        if (!empty($request->plats)) {
            $sitePlats = array_combine($platParam['id'], $platParam['rate']);
        } else {
            $sitePlats = [];
        }

        $plats = $site->agent ? $site->agent->mainGamePlats : MainGamePlat::all();
        $syncParams = [];
        foreach ($plats as $plat) {
            $status = in_array($plat->id, array_keys($sitePlats)) ? 1 : 0;
            if ($status) {
                $syncParams[$plat->id] = ['status' => $status, 'rate' => $sitePlats[$plat->id]];
                if (array_key_exists($plat->id, $sitePlats)) {
                    $platArr = $plat->toArray();
                    $rate = array_key_exists('pivot', $platArr) ? $platArr['pivot']['rate'] : $platArr['rate'];
                    if ($sitePlats[$plat->id] < $rate) {
                        return Redirect::back()->withInput()->with('danger', $plat->main_game_plat_name . '比率不能小于系统加分比率' . $rate);
                    }
                }

            } else {
                $syncParams[$plat->id] = ['status' => $status];
            }

        }

        $site->MainGamePlat()->sync($syncParams);

        if (!empty($site) && !empty($user)) {
            if (!$site->status) {
                $user->delete();
            }
            DB::commit();
            return redirect()->route('site.index')->with('success', '添加成功.');
        } else {
            DB::rollBack();
        }

    }

    /**
     * gameapi
     * 2018/11/1 14:00
     * Administrator
     * show
     * Display the specified resource.
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Site $site)
    {
        $plats = $site->MainGamePlat()->where('conf_site_main_game_plats.status', 1)->get()->toArray();
        return view('backend.game.site.show', compact('site', 'plats'));
    }

    /**
     * gameapi
     * 2018/10/8 14:49
     * Administrator
     * edit
     * Show the form for editing the specified resource.
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function edit(Site $site)
    {
        $this->authorize('update', $site);
        if ($site->agent) {
            $plats = $site->agent->mainGamePlats()->where('conf_agent_main_game_plats.status', 1)->get()->toArray();
        } else {
            $plats = MainGamePlat::status()->get()->toArray();
        }
        $sitePlats = $site->MainGamePlat()->where('conf_site_main_game_plats.status', 1)->get()->toArray();

        return view('backend.game.site.create_and_edit', compact('site', 'sitePlats', 'plats'));
    }

    /**
     * gameapi
     * 2018/10/8 14:50
     * Administrator
     * update
     * Update the specified resource in storage.
     * @param SiteRequest $request
     * @param Site $site
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(SiteRequest $request, Site $site)
    {
        $this->authorize('update', $site);
        $result = $site->update($request->only(['is_external', 'status', 'site_name']));

        //创建网站平台关联
        if (!empty($request->plats)) {
            $sitePlats = array_combine($request->plats['id'], $request->plats['rate']);
        } else {
            $sitePlats = [];
        }
        $plats = $site->agent ? $site->agent->mainGamePlats : MainGamePlat::all();
        if (empty($site->token)) {
            $site->token = encrypt($site->user->name . $site->username);
            $site->save();
        }
        $syncParams = [];
        foreach ($plats as $plat) {
            $status = in_array($plat->id, array_keys($sitePlats)) ? 1 : 0;
            if ($status) {
                $syncParams[$plat->id] = ['status' => $status, 'rate' => $sitePlats[$plat->id]];
                if (array_key_exists($plat->id, $sitePlats)) {
                    $platArr = $plat->toArray();
                    $rate = array_key_exists('pivot', $platArr) ? $platArr['pivot']['rate'] : $platArr['rate'];
                    if ($sitePlats[$plat->id] < $rate) {
                        return Redirect::back()->withInput()->with('danger', $plat->main_game_plat_name . '比率不能小于系统加分比率' . $rate);
                    }
                }
            } else {
                $syncParams[$plat->id] = ['status' => $status];
            }

        }

        $site->MainGamePlat()->sync($syncParams);

        if ($site->status) {
            $site->user()->restore();
        } else {
            $site->user()->delete();
        }

        if (!empty($result)) {
            return redirect()->route('site.index')->with('success', '修改成功.');
        }
    }

    /**
     * gameapi
     * 2018/10/8 14:50
     * Administrator
     * destroy
     * Remove the specified resource from storage.
     * @param Site $site
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function destroy(Site $site)
    {
        $this->authorize('destroy', $site);
        DB::beginTransaction();

        if ($site->user()->count() > 0) {
            $delUser = $site->user()->forceDelete();
        } else {
            $delUser = true;
        }
        if ($site->MainGamePlat->count() > 0) {
            $delPlat = $site->MainGamePlat()->detach();
        } else {
            $delPlat = true;
        }

        if ($site->playerBetFlows->count() > 0) {
            $delBetFlow = $site->playerBetFlows()->delete();
        } else {
            $delBetFlow = true;
        }

        if ($site->Players->count() > 0) {
            $delPlayer = $site->Players()->delete();
        } else {
            $delPlayer = true;
        }

        $delSite = $site->delete();
        if ($delSite && $delUser && $delPlat && $delBetFlow && $delPlayer) {
            DB::commit();
            return redirect()->route('site.index')->with('success', '删除成功.');
        } else {
            DB::rollBack();
            return redirect()->route('site.index')->with('danger', '删除失败！受影响行数为0！.');

        }

    }

    /**
     * gameapi
     * 2018/11/3 14:36
     * Administrator
     * batchDestroy
     * 批量删除
     * @param Request $request
     * @param Site $site
     * @return mixed
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function batchDestroy(Request $request, Site $site)
    {
        $this->authorize('destroy', $site);
        $ids = json_decode($request->getContent(), true);

        if (!empty($ids)) {
            DB::beginTransaction();
            foreach ($ids as $id) {

                if (Site::find($id)->user()->count() > 0) {
                    $user = Site::find($id)->user()->forceDelete();
                } else {
                    $user = true;
                }

                if ($site->MainGamePlat->count() > 0) {
                    $delPlat = Site::find($id)->MainGamePlat()->detach();
                } else {
                    $delPlat = true;
                }

                if ($site->playerBetFlows->count() > 0) {
                    $delBetFlow = $site->playerBetFlows()->delete();
                } else {
                    $delBetFlow = true;
                }

                if ($site->Players->count() > 0) {
                    $delPlayer = $site->Players()->delete();
                } else {
                    $delPlayer = true;
                }

                if (!$user || !$delPlat || !$delBetFlow || !$delPlayer) {
                    DB::rollBack();
                    return $this->response->array([
                            'status_code' => 500,
                            'message' => '删除失败！受影响行数为0！',
                        ]
                    );
                }
            }
            $result = Site::whereIn('id', $ids)->delete();
            if ($result) {
                DB::commit();
                return $this->response->array([
                        'status_code' => 200,
                        'message' => '删除成功！受影响行数：' . $result,
                    ]
                );
            } else {
                DB::rollBack();
                return $this->response->array([
                        'status_code' => 500,
                        'message' => '删除失败！受影响行数为0！',
                    ]
                );
            }
        }
    }

    /**
     * gameapi
     * 2018/10/8 14:51
     * Administrator
     * bonusPoint
     * 加分页
     * @param Request $request
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function bonusPoint(Request $request, Site $site)
    {
        $this->authorize('bonusPoint', $site);
        $siteIds = $this->getCurrentUserSite();

        if (!in_array($request->site_id, $siteIds) && !empty($request->site_id)) {
            return redirect()->route('site.bonus_point')->with('message', '没有权限查看次网站信息.');
        }
        $sites = Site::whereIn('id', $siteIds)->get();
        $siteId = $request->site_id ? $request->site_id : array_first($siteIds);
        $site = Site::with([
                'agent', 'MainGamePlat' => function ($query) {
                    $query->where('conf_site_main_game_plats.status', 1);
                }
            ]
        )
            ->find($siteId);

        return view('backend.game.site.bonus_point', compact('sites', 'site'));
    }

    /**
     * gameapi
     * 2018/11/2 15:50
     * Administrator
     * bonusPointUpdate
     * 加分操作
     * @param Site $site
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function bonusPointUpdate(Site $site, Request $request)
    {
        $this->authorize('bonusPoint', $site);
        $valid = $this->validate($request, [
                'plat_id' => 'required|numeric',
                'money' => 'required|numeric',
            ]
        );

        $sitePlate = $site
            ->MainGamePlat()
            ->where('conf_site_main_game_plats.main_game_plats_id', $valid['plat_id'])
            ->first();

        $addScore = $valid['money'] / $sitePlate->pivot->rate;


        //加分日志数据
        $logSiteScore['site_id'] = $site->id;
        $logSiteScore['main_game_plats_id'] = $valid['plat_id'];
        $logSiteScore['transferid'] = Uuid::uuid4()->getHex();
        $logSiteScore['rate'] = $sitePlate->pivot->rate;
        $logSiteScore['recharge_money'] = $valid['money'];
        $logSiteScore['recharge_score'] = $addScore;
        $logSiteScore['original'] = $sitePlate->pivot->score;
        $logSiteScore['change'] = $sitePlate->pivot->score + $addScore;
        $logSiteScore['before_money'] = $site->money;
        $logSiteScore['now_money'] = isset($request->money) ? ($site->money - $valid['money']) : $site->money;
        $logSiteScore['op'] = SiteScore::SITE_PLAT_BONUS_POINT;

        //分红计算（请不要修改顺序）
        $earning['agent_id'] = $site->agent ? $site->agent->id : 0;
        $earning['plat_id'] = $valid['plat_id'];
        $earning['site_id'] = $site->id;
        $earning['rate'] = $site->agent ? $site->agent->rate : 0;
        $earning['money'] = $valid['money'];
        $earning['site_rate'] = $sitePlate->pivot->rate;
        $earning['score'] = $addScore;
        $earning['plat_rate'] = $sitePlate->rate;
        $earning['earnings_money'] = ($valid['money'] - $sitePlate->rate * $addScore) * $earning['rate'];
        $earning['sys_earnings_money'] = $valid['money'] - $sitePlate->rate * $addScore;
        $earning['sys_net_earnings_money'] = ($valid['money'] - $sitePlate->rate * $addScore) - $earning['earnings_money'];
        $earning['before_money'] = $site->agent ? $site->agent->money : 0;
        $earning['after_money'] = $site->agent ? $site->agent->money + $earning['earnings_money'] : 0;


        //处理同步网站平台数据
        $sitePlateIds = $site->MainGamePlat()->pluck('main_game_plats_id')->toArray();
        $sitePlateIds = array_combine(array_values($sitePlateIds), array_values($sitePlateIds));
        $sitePlateIds[$valid['plat_id']] = ['score' => $sitePlate->pivot->score + $addScore];
        //数据库事务处理
        DB::beginTransaction();
        $siteScoreResult = SiteScore::create($logSiteScore);
        $earning['site_score_id'] = $siteScoreResult->id;
        $earning = Earning::create($earning);
        $siteScorePlatResult = $site->MainGamePlat()->sync($sitePlateIds);
        //钱转分时，扣除网站金额
        if ($site->money - $valid['money'] >= 0) {
            $site->money = $site->money - $valid['money'];
            $siteResult = $site->save();
        } else {
            DB::rollBack();
            return redirect()->route('site.bonus_point', ['site_id' => $site->id])->with('message', '加分失败:网站余额不够.');
        }


        if ($siteScoreResult && $siteScorePlatResult && $siteResult && $earning) {
            DB::commit();
            return redirect()->route('site.bonus_point', ['site_id' => $site->id])->with('success', '加分成功.');
        } else {
            DB::rollBack();
            return redirect()->route('site.bonus_point', ['site_id' => $site->id])->with('message', '加分失败.');
        }


    }

    /**
     * gameapi
     * 2018/10/8 14:52
     * Administrator
     * bonusPointLog
     * 加分日志
     * @param Request $request
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function bonusPointLog(Request $request, Site $site)
    {
        $this->authorize('bonusPointLog', $site);

        $limit = $request->limit ?? config('administrator.paginate.limit');

        $startTime = empty($request->only('created_at_start')) ? Carbon::now()->startOfWeek()->toDateTimeString() : $request->created_at_start;
        $endTime = empty($request->only('created_at_end')) ? Carbon::now()->toDateTimeString() : $request->created_at_end;
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<=', $endTime],
        ];
        $params = [
            'created_at_start' => $startTime,
            'created_at_end' => $endTime,
            'transferid' => '',
            'site_name' => '',
            'main_game_plat_code' => '',
            'status' => null
        ];

        if (!empty($request->transferid)) {
            $where[] = ['transferid', '=', $request->transferid];
            $params['transferid'] = $request->transferid;
        }

        if (isset($request->status)) {
            $where[] = ['status', '=', (integer)$request->status];
            $params['status'] = (integer)$request->status;
        }

        $siteIds = $this->getCurrentUserSite();
        //检查用户是否有权限查看此网站信息
        if (!empty($request->site_username)) {
            $siteId = Site::where('username', $request->site_username)->first()->id;
            if (!in_array($siteId, $siteIds)) {
                return redirect()->route('site.bonus_point_log')->with('message', '没有权限查看次网站信息.');
            }
        }
        $score = SiteScore::whereIn('site_id', $siteIds)
            ->where($where)
            ->whereHas(
                'Site', function ($query) use ($request, &$params) {
                if (!empty($request->site_name)) {
                    $params['site_name'] = $request->site_name;
                    $query->where('username', '=', $request->site_name);
                }
            }
            )->whereHas('MainGamePlat', function ($query) use ($request, &$params) {
                if (!empty($request->main_game_plat_code)) {
                    $params['main_game_plat_code'] = $request->main_game_plat_code;
                    $query->where('main_game_plat_code', '=', $request->main_game_plat_code);
                }
            }
            )->with('Site', 'MainGamePlat');
        $siteScores = (clone $score)->paginate((integer)$limit);
        $sumParams['recharge_money'] = (clone $score)->sum('recharge_money');
        $plats = MainGamePlat::whereHas('site', function ($query) use ($siteIds) {
            $query->whereIn('conf_sites.id', $siteIds)->where('conf_site_main_game_plats.status', 1);
        }
        )->status()->get();

        return view('backend.game.site.bonus_point_log', compact('siteScores', 'limit', 'params', 'sumParams', 'plats'));
    }


    /**
     * gameapi
     * 2018/11/3 17:43
     * Administrator
     * adminDeposit
     *
     */
    public function adminDeposit(Site $site)
    {
        $site = $site->with([
                'agent', 'MainGamePlat' => function ($query) {
                    $query->where('conf_site_main_game_plats.status', 1);
                }
            ]
        )
            ->find($site->id);

        return view('backend.game.site.admin_deposit', compact('site'));
    }

    /**
     * gameapi
     * 2018/11/3 21:15
     * Administrator
     * adminDepositStore
     * 管理员充值保存
     * @param Request $request
     * @param Site $site
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function adminDepositStore(Request $request, Site $site)
    {
        $valid = $this->validate($request, [
                'pay_order' => 'required|string',
                'account' => 'required|string',
                'pay_type' => 'required|in:1,2,3',
                'to_account' => 'required|string',
                'money' => 'required|numeric',
            ]
        );
        DB::beginTransaction();
        $siteDeposit = SiteDeposit::create([
                'site_id' => $site->id,
                'user_id' => \Auth::id(),
                'money' => $valid['money'],
                'before_money' => $site->money,
                'after_money' => $site->money + $valid['money'],
                'transferid' => Uuid::uuid4(),
                'pay_order' => $valid['pay_order'],
                'account' => $valid['account'],
                'to_account' => $valid['to_account'],
                'pay_type' => $valid['pay_type'],
                'confirm_at' => Carbon::now()->toDateTimeString(),
                'pay_status' => 1,
            ]
        );

        $site->money = $site->money + $valid['money'];
        $saveResult = $site->save();
        if ($siteDeposit && $saveResult) {
            DB::commit();
            return redirect()->route('site.index')->with('success', '充值成功');
        } else {
            DB::rollBack();
            return redirect()->back()->withInput()->with('danger', '没有权限查看次网站信息.');
        }
    }

    /**
     * gameapi
     * 2018/10/10 9:26
     * Administrator
     * depositLog
     * 存款日志
     * @param Request $request
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function depositLog(Request $request, Site $site)
    {
        $this->authorize('depositLog', $site);
        $limit = $request->limit ?? config('administrator.paginate.limit');

        $startTime = empty($request->only('created_at_start')) ? Carbon::now()->startOfWeek()->toDateTimeString() : $request->created_at_start;
        $endTime = empty($request->only('created_at_end')) ? Carbon::now()->toDateTimeString() : $request->created_at_end;
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<=', $endTime],
        ];
        $params = [
            'created_at_start' => $startTime,
            'created_at_end' => $endTime,
            'transferid' => '',
            'site_name' => '',
        ];

        if (!empty($request->transferid)) {
            $where[] = ['transferid', '=', $request->transferid];
            $params['transferid'] = $request->transferid;
        }

        $siteIds = $this->getCurrentUserSite();
        //检查用户是否有权限查看此网站信息
        if (!empty($request->site_username)) {
            $siteId = Site::where('username', $request->site_username)->first()->id;
            if (!in_array($siteId, $siteIds)) {
                return redirect()->route('site.bonus_point_log')->with('message', '没有权限查看次网站信息.');
            }
        }
        $deposit = SiteDeposit::whereIn('site_id', $siteIds)
            ->where($where)
            ->whereHas(
                'site', function ($query) use ($request, &$params) {
                if (!empty($request->site_name)) {
                    $params['site_name'] = $request->site_name;
                    $query->where('username', '=', $request->site_name);
                }
            }
            )->with('Site');
        $siteDeposits = (clone $deposit)->paginate((integer)$limit);
        $sumParams['money'] = (clone $deposit)->sum('money');

        return view('backend.game.site.deposit_log', compact('siteDeposits', 'limit', 'params', 'sumParams'));
    }

    /**
     * gameapi
     * 2018/10/8 12:27
     * Administrator
     * getCurrentUserSite
     * 获取当前用户所属网站id
     * @return array
     */
    private function getCurrentUserSite()
    {
        $user = \Auth::user();
        $type = $user->type;
        if ($type === 0) {
            $siteIds = Site::all()->pluck('id')->toArray();
        } elseif ($type == 1) {
            $siteIds = $user->agent->sites()->get()->pluck('id')->toArray();
        } elseif ($type = 2) {
            $siteIds = $user->site()->get()->pluck('id')->toArray();
        }

        return $siteIds;
    }

    /**
     * gameapi
     * 2019/1/4 16:46
     * Administrator
     * platMutualTransfer
     * 平台互相转分
     * @param Request $request
     * @param Site $site
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function platMutualTransfer(Request $request, Site $site)
    {
        $this->authorize('platMutualTransfer', $site);

        $siteIds = $this->getCurrentUserSite();

        if (!in_array($request->site_id, $siteIds) && !empty($request->site_id)) {
            return redirect()->route('site.bonus_point')->with('message', '没有权限查看次网站信息.');
        }
        $sites = Site::whereIn('id', $siteIds)->get();
        $siteId = $request->site_id ? $request->site_id : array_first($siteIds);
        $site = Site::with([
                'agent', 'MainGamePlat' => function ($query) {
                    $query->where('conf_site_main_game_plats.status', 1);
                }
            ]
        )
            ->find($siteId);

        return view('backend.game.site.plat_mutual_transfer', compact('site', 'sites'));
    }

    /**
     * gameapi
     * 2019/1/4 16:46
     * Administrator
     * platMutualTransferStore
     *
     * @param Request $request
     * @param Site $site
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function platMutualTransferStore(Request $request, Site $site)
    {
        $this->authorize('platMutualTransfer', $site);

        $valid = $this->validate($request, [
                'to_plat_id' => 'required|numeric',
                'in_plat_id' => 'required|numeric',
                'score' => 'required_without:money|numeric',
            ]
        );

        $sitePlateIn = $site
            ->MainGamePlat()
            ->where('conf_site_main_game_plats.main_game_plats_id', $valid['in_plat_id'])
            ->first();
        $sitePlateOut = $site
            ->MainGamePlat()
            ->where('conf_site_main_game_plats.main_game_plats_id', $valid['to_plat_id'])
            ->first();


        $addScore = $valid['score'];
        $transferId=Uuid::uuid4()->getHex();

        if($addScore<=0){
            return redirect()->route('site.plat_mutual_transfer', ['site_id' => $site->id])->with('message', '互转失败:互转分数必须大于0.');
        }

        if($valid['in_plat_id']===$valid['to_plat_id']){
            return redirect()->route('site.plat_mutual_transfer', ['site_id' => $site->id])->with('message', '互转失败:转入转出平台不能相同.');
        }
        //钱转分时，扣除网站金额
        if ($sitePlateOut->pivot->score - $addScore < 0) {
            return redirect()->route('site.plat_mutual_transfer', ['site_id' => $site->id])->with('message', '互转失败:转出平台余额不够.');
        }
        //转出日志数据
        $logSiteScoreOut['site_id'] = $site->id;
        $logSiteScoreOut['main_game_plats_id'] = $valid['to_plat_id'];
        $logSiteScoreOut['transferid'] = $transferId;
        $logSiteScoreOut['rate'] = $sitePlateOut->pivot->rate;
        $logSiteScoreOut['recharge_money'] = 0;
        $logSiteScoreOut['recharge_score'] = -$addScore;
        $logSiteScoreOut['original'] = $sitePlateOut->pivot->score;
        $logSiteScoreOut['change'] = $sitePlateOut->pivot->score - $addScore;
        $logSiteScoreOut['before_money'] = $site->money;
        $logSiteScoreOut['now_money'] = $site->money;
        $logSiteScoreOut['op'] = SiteScore::SITE_PLAT_MUTUAL_TRANSFER_OUT;

        //转入日志数据
        $logSiteScoreIn['site_id'] = $site->id;
        $logSiteScoreIn['main_game_plats_id'] = $valid['in_plat_id'];
        $logSiteScoreIn['transferid'] = $transferId;
        $logSiteScoreIn['rate'] = $sitePlateIn->pivot->rate;
        $logSiteScoreIn['recharge_money'] = 0;
        $logSiteScoreIn['recharge_score'] = ($sitePlateOut->pivot->rate*$addScore)/$sitePlateIn->pivot->rate;
        $logSiteScoreIn['original'] = $sitePlateIn->pivot->score;
        $logSiteScoreIn['change'] = $sitePlateIn->pivot->score + $addScore;
        $logSiteScoreIn['before_money'] = $site->money;
        $logSiteScoreIn['now_money'] = $site->money;
        $logSiteScoreIn['op'] = SiteScore::SITE_PLAT_MUTUAL_TRANSFER_IN;


        //处理同步网站平台数据
        $sitePlateIds = $site->MainGamePlat()->pluck('main_game_plats_id')->toArray();
        $sitePlateIds = array_combine(array_values($sitePlateIds), array_values($sitePlateIds));
        $sitePlateIds[$valid['to_plat_id']] = ['score' => $sitePlateOut->pivot->score - $addScore];
        $sitePlateIds[$valid['in_plat_id']] = ['score' => $sitePlateIn->pivot->score + ($sitePlateOut->pivot->rate*$addScore)/$sitePlateIn->pivot->rate];
        //数据库事务处理
        DB::beginTransaction();
        $siteScoreInResult = SiteScore::create($logSiteScoreIn);
        $siteScoreOutResult = SiteScore::create($logSiteScoreOut);
        $siteScorePlatResult = $site->MainGamePlat()->sync($sitePlateIds);

        if ($siteScoreOutResult &&  $siteScoreInResult && $siteScorePlatResult  ) {
            DB::commit();
            return redirect()->route('site.bonus_point', ['site_id' => $site->id])->with('success', '互转成功.');
        } else {
            DB::rollBack();
            return redirect()->route('site.bonus_point', ['site_id' => $site->id])->with('message', '互转失败.');
        }
    }
}
